<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 17-11-2
 * Time: 下午4:20
 */
namespace CloudHash;

class Server{
    public $socket;
    public $storage;
    public function __construct($port){
        $this->socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
        socket_bind($this->socket,'0.0.0.0',$port);
        socket_listen($this->socket);

        $address = '';
        $port = 0;
        socket_getsockname($this->socket,$address,$port);
        echo "listen on port {$port}";
        $this->storage = [];
    }

    public function start(){
        do{
            $conn = socket_accept($this->socket);
            $this->handle($conn);
            socket_close($conn);
        }while(true);
    }

    public function handle($conn){
        $request = socket_read($conn,1024);
        $response = $this->process($request);
        socket_write($conn,$response);
    }

    public function process($request){
        $response = '';
        $command = '';
        $key = '';
        $value = null;
        list($command,$key,$value) = explode(' ',$request);
        $command = strtoupper($command);

        switch ($command){
            case 'GET':
                $response = isset($this->storage[$key])?$this->storage[$key]:null;
                break;
            case 'SET';
                $this->storage[$key] = $value;
                $response = $value;
                break;
        }

        return $response;

    }
}

$server = new Server(4481);
$server->start();